<template>
	<van-tabbar v-model="selectedTab" fixed @change="onChange">
		<van-tabbar-item v-for="item in tabbarItems" :key="item.routeName" :icon="item.icon">
			{{ item.title }}
		</van-tabbar-item>
	</van-tabbar>
</template>

<script>
	import {
		Tabbar,
		TabbarItem
	} from 'vant';

	export default {
		components: {
			VanTabbar: Tabbar,
			VanTabbarItem: TabbarItem
		},
		data() {
			return {
				selectedTab: 0,
				tabbarItems: [{
						title: "首页",
						routeName: "home",
						icon: "home-o"
					},
					{
						title: "商品",
						routeName: "verticalTabs",
						icon: "gift-o"
					},
					{
						title: "购物车",
						routeName: "shopcart",
						icon: "shopping-cart-o"
					},
					{
						title: "我的",
						routeName: "user",
						icon: "user-o"
					}
				]
			};
		},
		mounted() {
			try {
				// 初始化时匹配当前路由对应的选中项
				const currentIndex = this.tabbarItems.findIndex(
					item => item.routeName === this.$route.name
				);
				if (currentIndex !== -1 && currentIndex !== this.selectedTab) {
					this.selectedTab = currentIndex;
				}
			} catch (error) {
				console.error('FooterNav初始化错误:', error);
			}
		},
		methods: {
			onChange(index) {
				try {
					const targetRoute = this.tabbarItems[index]?.routeName;
					if (!targetRoute) return;

					// 避免重复跳转同一路由
					if (targetRoute === this.$route.name) return;

					this.$router.push({
						name: targetRoute
					}).catch(error => {
						if (!error.message.includes('NavigationDuplicated')) {
							console.error('路由跳转出错:', error);
						}
					});
				} catch (error) {
					console.error('FooterNav切换错误:', error);
				}
			}
		}
	};
</script>

<style scoped>
	/* 可根据需求添加样式 */
	.van-tabbar {
		border-top: 1px solid #eee;
	}
</style>